package com.yqkj.modules.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.yqkj.common.utils.R;
import com.yqkj.modules.sys.entity.LoginForm;
import com.yqkj.modules.sys.entity.SysUserEntity;
import com.yqkj.modules.sys.service.SysUserService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * @author wuyj
 * @email wuyj298@163.com
 * @date 2018年07月12 19:10
 */
@RestController
public class SysLoginController extends AbstractController{

    @Autowired
    private Producer producer;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 生成验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "captcha.jpg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);

        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    @PostMapping(value = "/sys/login")
    public Map<String, Object> login(@RequestBody LoginForm loginForm, HttpServletRequest request) {
        Object kaptcha = request.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        if (kaptcha != null) {
            if (!loginForm.getCaptcha().equalsIgnoreCase(kaptcha.toString())) {
                return R.error("验证码不正确");
            }
        } else {
           return R.error("验证码过期");
        }

        //根据用户查询记录
       SysUserEntity sysUserEntity = sysUserService.querySysUserByUserName(loginForm.getUsername());


       /* if (null != sysUserEntity && ()) {

        }*/

        return new R();
    }

    public static void main(String[] args) {
      //   new Sha256Hash();
    }
}
